<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch">
      <el-form-item label="类目名称" prop="name">
        <el-input
          v-model="queryParams.name"
          placeholder="请输入类目名称"
          clearable
          maxlength="200"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="状态" prop="enable">
        <el-select v-model="queryParams.enable" placeholder="类目状态" clearable>
          <el-option
            v-for="dict in dict.type.category_normal_disable"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['shop:goodscategory:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="info" plain icon="el-icon-sort" size="mini" @click="toggleExpandAll">展开/折叠</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table
      v-if="refreshTable"
      v-loading="loading"
      :data="categoryList"
      row-key="id"
      :default-expand-all="isExpandAll"
      :tree-props="{children: 'children', hasChildren: 'hasChildren'}"
    >
      <el-table-column prop="name" label="类目名称" :show-overflow-tooltip="true" width="300"></el-table-column>
      <el-table-column prop="picUrl" label="图片" align="center" width="160">
        <template slot-scope="scope">
          <el-image
            style="width: 50px; height: 50px;"
            :src="scope.row.picUrl"
            :preview-src-list="[scope.row.picUrl]"
          />
        </template>
      </el-table-column>
      <el-table-column prop="sort" label="排序" width="80"></el-table-column>
      <el-table-column prop="enable" label="状态" width="80">
        <template slot-scope="scope">
          <el-switch
            v-model="scope.row.enable"
            active-value="1"
            inactive-value="0"
            @change="handleStatusChange(scope.row)"
          ></el-switch>
        </template>
      </el-table-column>
      <el-table-column label="创建时间" align="center" prop="createDate">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.createDate) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['shop:goodscategory:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-plus"
            @click="handleAdd(scope.row)"
            v-hasPermi="['shop:goodscategory:add']"
          >新增</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['shop:goodscategory:remove']"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <image-selector
      :dialogVisible.sync="showImageSelector"
      @confirm="onImageSelectorConfirm($event)"
    ></image-selector>
    <!-- 添加或修改类目对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="680px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="100px">
        <el-row>
          <el-col :span="24">
            <el-form-item label="上级类目">
              <treeselect
                v-model="form.parentId"
                :options="categoryOptions"
                :normalizer="normalizer"
                :show-count="true"
                placeholder="选择上级类目"
              />
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="类目名称" prop="name">
              <el-input v-model="form.name" placeholder="请输入类目名称"/>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="类目图片" prop="picUrl">
              <el-input v-model="form.picUrl" v-show="false"/>
              <img
                v-if="form.picUrl"
                :src="form.picUrl"
                alt
                style="width: 100px; height: 100px;cursor: pointer;"
                @click="addImg"
              >
              <el-button v-else type="primary" icon="el-icon-plus" @click="addImg"></el-button>
            </el-form-item>
          </el-col>

          <el-col :span="12">
            <el-form-item label="显示排序" prop="sort">
              <el-input-number
                v-model="form.sort"
                controls-position="right"
                :min="0"
                :max="10000"
                :precision="0"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item>
              <span slot="label">
                <el-tooltip content="选择隐藏该类目将不会出现在客户端" placement="top">
                  <i class="el-icon-question"></i>
                </el-tooltip>显示状态
              </span>
              <el-radio-group v-model="form.enable">
                <el-radio
                  v-for="dict in dict.type.category_normal_disable"
                  :key="dict.value"
                  :label="dict.value"
                >{{dict.label}}</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  list,
  get,
  del,
  add,
  update,
  enableCategory
} from "@/api/shop/category";
import Treeselect from "@riophae/vue-treeselect";
import "@riophae/vue-treeselect/dist/vue-treeselect.css";
import ImageSelector from "@/components/ImageSelector";

export default {
  name: "Category",
  dicts: ["category_normal_disable"],
  components: { ImageSelector, Treeselect },
  data() {
    return {
      // 遮罩层
      loading: true,
      // 显示搜索条件
      showSearch: true,
      // 类目表格树数据
      categoryList: [],
      // 类目树选项
      categoryOptions: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 显示选择图片
      showImageSelector: false,
      // 是否展开，默认全部折叠
      isExpandAll: false,
      // 重新渲染表格状态
      refreshTable: true,
      // 查询参数
      queryParams: {
        name: undefined,
        enable: undefined
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        name: [
          { required: true, message: "类目名称不能为空", trigger: "blur" }
        ],
          picUrl: [
            { required: true, message: "请选择类目图片", trigger: "change" }
          ],
        sort: [
          {
            required: true,
            message: "类目顺序不能为空",
            trigger: ["blur", "change"]
          }
        ]
      }
    };
  },
  created() {
    this.getList();
  },
  methods: {
    // 选择图标
    selected(name) {
      this.form.icon = name;
    },
    /** 查询类目列表 */
    getList() {
      this.loading = true;
      list(this.queryParams).then(response => {
        this.categoryList = this.handleTree(response.data, "id");
        this.loading = false;
      });
    },
    /** 转换类目数据结构 */
    normalizer(node) {
      if (node.children && !node.children.length) {
        delete node.children;
      }
      return {
        id: node.id,
        label: node.name,
        children: node.children
      };
    },
    /** 查询类目下拉树结构 */
    getTreeselect() {
      list().then(response => {
        this.categoryOptions = [];
        const category = { id: 0, name: "主类目", children: [] };
        category.children = this.handleTree(response.data, "id");
        this.categoryOptions.push(category);
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: undefined,
        parentId: 0,
        name: undefined,
        sort: 0,
        isFrame: "1",
        isCache: "0",
        enable: "0",
        picUrl: undefined
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    /** 新增按钮操作 */
    handleAdd(row) {
      this.reset();
      this.getTreeselect();
      if (row != null && row.id) {
        this.form.parentId = row.id;
      } else {
        this.form.parentId = 0;
      }
      this.open = true;
      this.title = "添加类目";
    },
    /** 展开/折叠操作 */
    toggleExpandAll() {
      this.refreshTable = false;
      this.isExpandAll = !this.isExpandAll;
      this.$nextTick(() => {
        this.refreshTable = true;
      });
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      this.getTreeselect();
      get(row.id).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改类目";
      });
    },
    // 类目状态修改
    handleStatusChange(row) {
      let text = row.enable === "0" ? "停用" : "启用";
      this.$modal
        .confirm("确认要" + text + '"' + row.name + '"类目吗？')
        .then(() => {
          this.changeCategoryStatus(row.id, row.enable);
        })
        .catch(() => {
          row.enable = row.enable === "0" ? "1" : "0";
        });
    },
    changeCategoryStatus: function(id, enable) {
      var param = {
        id: id,
        enable: enable
      };
      enableCategory(param).then(response => {
        this.getList();
      });
    },
    /** 提交按钮 */
    submitForm: function() {
      this.$refs["form"].validate(valid => {
        if (valid) {
            let selectedNode = ''
            const parentId = this.form.parentId
            const nodeList = this.categoryOptions
            let findNodeById = function(nodePid, list) {
              for (let node of list) {
                if (node.id == nodePid) {
                  selectedNode = node
                }
                if (node.children && node.children.length > 0) {
                  findNodeById(nodePid, node.children)
                }
              }
            }
            findNodeById(parentId, nodeList);
            if (selectedNode.level >=10 ) {
              this.$modal.msgError('类目层级最多允许十级')
              return
            }
          if (this.form.id != undefined) {
            update(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            add(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      this.$modal
        .confirm('是否确认删除名称为"' + row.name + '"的数据项？')
        .then(function() {
          return del(row.id);
        })
        .then(() => {
          this.getList();
          this.$modal.msgSuccess("删除成功");
        })
        .catch(() => {});
    },
    /**
     * 添加图片
     */
    addImg() {
      this.showImageSelector = true;
    },
    /**
     * 选中图片确认
     */
    onImageSelectorConfirm(selectedItem) {
      this.form.picUrl = selectedItem.url;
    }
  }
};
</script>
